package com.itlong.cloud.controller.system;


import com.itlong.cloud.POJO.DTO.property.PropertyGroupGetPageDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyUserInfoGetPageDTO;
import com.itlong.cloud.POJO.PO.PropertyGroupPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyUserInfoGetUserPageVO;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.property.IPropertyGroupServiceClient;
import com.itlong.cloud.user.property.IPropertyUserServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      物业系统部门管理Controller
 * </desc>
 *
 * @createDate 2017/10/16
 */
@RestController
@RequestMapping("/system/group")
public class PropertyGroupController {

    @Autowired
    IPropertyGroupServiceClient iPropertyGroupServiceClient;

    @Autowired
    IPropertyUserServiceClient iPropertyUserServiceClient;
    /**
     * <desc>
     *      获取分页列表
     * </desc>
     *@param pageDTO 部门分页DTO
     * @return MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "/getPage")
    @ResponseBody
    @AuthAccessRequired
    public Object getPage(PropertyGroupGetPageDTO pageDTO){
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyGroupGetPageDTO.class, request);
            if(StringUtils.isBlank(pageDTO.getProjectId())){
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_IS_ILLEGAL.getErrorCode());
            }
            Page<PropertyGroupPO> page = iPropertyGroupServiceClient.getPage(pageDTO);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_部门update】获取分页列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      保存部门
     * </desc>
     *
     * @param propertyGroupPO 部门PO
     * @return  MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "/save")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_SAVEGROUP_INFO_LOG_DESC)
    public Object save(PropertyGroupPO propertyGroupPO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyGroupPO = HttpProtocolUtil.parseRequestParamToDTO(PropertyGroupPO.class, request);
            if (propertyGroupPO == null || StringUtils.isBlank(propertyGroupPO.getGroupName())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //校验同一小区中是否已经存同名的部门
            Map<String,Object> params = new HashMap<>();
            params.put("groupName",propertyGroupPO.getGroupName());
            params.put("projectId",propertyGroupPO.getProjectId());
            List<PropertyGroupPO> groupList = iPropertyGroupServiceClient.getByFeilds(params);
            if(groupList !=null && !groupList.isEmpty()){
                return new MessageVO(PropertyErrorCodeEnum.USER_GROUP_GROUPNAME_EXIST.getErrorCode());
            }
            iPropertyGroupServiceClient.save(propertyGroupPO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_部门update】保存部门失败", e);
        }
    }

    /**
     * <desc>
     *      更新部门
     * </desc>
     *
     * @param propertyGroupPO 部门PO
     * @return MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "/update")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_UPDATEGROUP_INFO_LOG_DESC)
    public Object update(PropertyGroupPO propertyGroupPO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyGroupPO = HttpProtocolUtil.parseRequestParamToDTO(PropertyGroupPO.class, request);
            if (propertyGroupPO == null || StringUtils.isBlank(propertyGroupPO.getGroupName())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyGroupPO.getGroupId())) {
                return new MessageVO(PropertyErrorCodeEnum.USER_GROUP_GROUPID_NOT_NULL.getErrorCode());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("groupName", propertyGroupPO.getGroupName());
            params.put("projectId", propertyGroupPO.getProjectId());
            params.put("groupIdNot", propertyGroupPO.getGroupId());
            List<PropertyGroupPO> groupList = iPropertyGroupServiceClient.getByFeilds(params);
            if (groupList != null && !groupList.isEmpty()) {
                return new MessageVO(PropertyErrorCodeEnum.USER_GROUP_GROUPNAME_EXIST.getErrorCode());
            }
            iPropertyGroupServiceClient.update(propertyGroupPO);
            return new MessageVO(propertyGroupPO.getGroupId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_部门update】更新部门失败", e);
        }
    }

    /**
     * <desc>
     *      根据id查询部门
     * </desc>
     *
     * @param propertyGroupPO 部门PO
     * @return MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "/getOne")
    @ResponseBody
    public Object getOne(PropertyGroupPO propertyGroupPO){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyGroupPO = HttpProtocolUtil.parseRequestParamToDTO(PropertyGroupPO.class, request);
            propertyGroupPO=iPropertyGroupServiceClient.getOne(propertyGroupPO);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),propertyGroupPO);
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_部门getOne】根据id查询部门失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      禁用或启用部门
     * </desc>
     *
     * @param propertyGroupPO 部门PO
     *
     * @return MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "/banOrUse")
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.USER_BANORUSERGROUP_INFO_LOG_DESC)
    public Object banOrUse(PropertyGroupPO propertyGroupPO){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyGroupPO = HttpProtocolUtil.parseRequestParamToDTO(PropertyGroupPO.class, request);
            iPropertyGroupServiceClient.banOrUse(propertyGroupPO);
            messageVO=new MessageVO(propertyGroupPO.getGroupId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_部门banOrUse】禁用或启用部门失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取所有部门
     * </desc>
     *@param    projectId  查询的小区ID
     * @return  MessageVO 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/10/16
     */
    @PostMapping(path = "/getList")
    @ResponseBody
    public Object getList(String projectId) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            if (StringUtils.isBlank(projectId)) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_IS_ILLEGAL.getErrorCode());
            }
            Map<String, Object> params = new HashMap<>();
            params.put("projectId", projectId);
            List<PropertyGroupPO> list = iPropertyGroupServiceClient.getByFeilds(params);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), list);
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_部门getList】获取所有部门失败", e);
        }
    }

    /**
     * <desc>
     *      获取分配人员列表
     * </desc>
     *
     * @param pageDTO1  查询参数DTO
     * @return
     * @author Biao.R
     * @createDate 2017/10/10
     */
    @PostMapping(path = "/getAllotUserPage")
    @ResponseBody
    public Object getAllotUserPage(PropertyUserInfoGetPageDTO pageDTO1){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO1 = HttpProtocolUtil.parseRequestParamToDTO(PropertyUserInfoGetPageDTO.class, request);
            PropertyUserInfoGetPageDTO pageDTO = pageDTO1;
            Page<PropertyUserInfoGetUserPageVO> page=iPropertyUserServiceClient.getPage(pageDTO);
            List<PropertyUserInfoGetUserPageVO> users =page.getRows();
            //检查是否已拥有该角色
            users.forEach(user->{
                if (user.getGroupId()!=null&&user.getGroupId().equals(pageDTO.getAllotGroupId())) {
                    user.setHaveGroup("true");
                }
            });
            page.setRows(users);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_部门getAllotUserPage】获取分配人员列表失败",e);
        }
        return messageVO;
    }


    /**
     * <desc>
     *      部门分配用户
     * </desc>
     *
     * @param groupId    部门id
     * @param allotUsers    需要分配的人员id 多个，号分隔
     * @param userIds 当前列表所有人员id 多个，号分隔
     * @return
     * @author Biao.R
     * @createDate 2017/10/10
     */
    @PostMapping(path = "/saveGroupUsers")
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.USER_SAVEGROUPUSERS_INFO_LOG_DESC)
    public Object saveGroupUsers(
            String groupId,
            String allotUsers,
            String userIds){
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            groupId = request.getAttribute("groupId") == null ? null : request.getAttribute("groupId").toString();
            allotUsers = request.getAttribute("allotUsers") == null ? "" : request.getAttribute("allotUsers").toString();
            userIds = request.getAttribute("userIds") == null ? null : request.getAttribute("userIds").toString();
            iPropertyGroupServiceClient.saveGroupUsers(groupId, allotUsers, userIds);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_部门saveGroupUsers】部门分配用户失败",e);
        }
    }


}
